import { getLocalStorage, setLocalStorage } from "../utils/storage";

const shopCar = {
  namespaced: true,
  state: {
    shopCar: getLocalStorage("shopCar")
  },

  mutations: {
    addToCar: (state, good) => {
      // 设置节流阀
      // 如果当前加入的数据已经在之前加入过了  那么只让数量累加
      let flag = false;
      state.shopCar.some(item => {
        if (item.id === good.id) {
          // 意味着当前数据已经存在   让数量累加  更新数量即可
          item.count += parseInt(good.count);
          flag = true;
          return true;
        }
      });
      // 若没找到   则加入shopCar
      if (!flag) {
        state.shopCar.push(good);
      }

      setLocalStorage("shopCar", state.shopCar);
    },
    // 更新数量 购物车模块更新数量
    updateList: (state, goods) => {
      state.shopCar.some(item => {
        if (item.id === goods.id) {
          item.count = parseInt(goods.count);
          return true;
        }
      });
      setLocalStorage("shopCar", state.shopCar);
    },
    // 删除
    remove: (state, id) => {
      state.shopCar.forEach((item, i) => {
        if (item.id === id) {
          state.shopCar.splice(i, 1);
        }
      });
      setLocalStorage("shopCar", state.shopCar);
    },
    // 修改选中状态
    updataSelected(state, goods) {
      state.shopCar.forEach(item => {
        if (item.id === goods.id) {
          item.select = goods.select;
        }
      });
      setLocalStorage("shopCar", state.shopCar);
    }
  },

  actions: {}
};

export default shopCar;
